using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Publicuse.Application;
using Geekeradmin.Authorize;
using Publicuse.Autofac;


using Publicuse.Interface;
using Publicuse.Util;
using Publicuse.Util.QuartZ;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Quartz;
using Quartz.Impl.Matchers;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Xml;
using Publicuse.Interface;
using Publicuse.Entity;
using Publicuse.Export;
using MySqlX.XDevAPI.Common;
using OfficeOpenXml.DataValidation;
using Publicuse.Interface.Extend;

namespace Geekeradmin.Controllers
{
    /// <summary>
    /// 系统任务调度模块管理
    /// </summary>
    [UserAuthorize("Admin"), AllowAnonymous]
    public class QuartzController : BaseController
    {

        private readonly ISchedulerFactory schedulerFactory;

        private readonly IJobFactory jobFactory;

        public QuartzController(IAutofaceInstance autoface, IMySqlSugarService mySqlSugar, IWebHostEnvironment webHost,
            IOptions<DBConnectionOption> options, ISchedulerFactory schedulerFactory, IJobFactory jobFactory, IBaseServiceExt baseServiceExt)
             : base(autoface, mySqlSugar, webHost, options, baseServiceExt)
        {
            this.jobFactory = jobFactory;
            this.schedulerFactory = schedulerFactory;
        }


        /// <summary>
        /// 获取后台作业信息列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// 
        [HttpPost("GetList")]
        public async Task<JsonResult> GetList(QuzrtTaskOptions query)
        {
            CommonResult result = await QuartzApplication.GetApplication(container).GetList(query);
            return new JsonResult(result);
        }

        /// <summary>
        /// 根据作业分组和任务名称获取作业状态
        /// </summary>
        /// <param name="GroupName"></param>
        /// <param name="TaskName"></param>
        /// <returns></returns>
        [HttpGet("GetJobStatus")]
        public async Task<JsonResult> GetJobStatus(string GroupName, string TaskName)
        {
            CommonResult result = await QuartzApplication.GetApplication(container).GetJobStatus(schedulerFactory, GroupName, TaskName);
            return new JsonResult(result);
        }

        /// <summary>
        /// 检查执行间隔格式是否正确
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpGet("CheckInterval")]
        public async Task<JsonResult> CheckInterval(string time)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                (bool, string) validExpression = time.IsValidExpression();
                if (!validExpression.Item1)
                {
                    result.msg = $"时间执行间隔格式不正确：{validExpression.Item2}，请检查！";
                }
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 新增修改后台作业信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost("AddOrUpdate")]
        public async Task<JsonResult> AddOrUpdate(QuzrtTaskOptions info)
        {
            CommonResult result = await QuartzApplication.GetApplication(container).AddOrUpdate(info);
            return new JsonResult(result);
        }

        /// <summary>
        /// 检查后台作业是否存在
        /// </summary>
        /// <param name="GroupName"></param>
        /// <param name="TaskName"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("Checkgtname"), AllowAnonymous]
        public async Task<JsonResult> Checkgtname(string GroupName, string TaskName, string loginUserCode, string Id = "")
        {
            CommonResult result = await QuartzApplication.GetApplication(container).Checkgtname(GroupName, TaskName, loginUserCode, Id);
            return new JsonResult(result);
        }

        /// <summary>
        /// 删除后台作业信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet("Delete")]
        public async Task<JsonResult> Delete(string Id, string loginUserCode, string type = "-9")
        {
            CommonResult result = await QuartzApplication.GetApplication(container).Delete(schedulerFactory, Id, loginUserCode, type);
            return new JsonResult(result);
        }

        /// <summary>
        /// 还原后台作业删除信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <returns></returns>
        [HttpGet("Reduction"), AllowAnonymous]
        public async Task<JsonResult> Reduction(string Id, string loginUserCode)
        {
            CommonResult result = await QuartzApplication.GetApplication(container).Reduction(Id, loginUserCode);
            return new JsonResult(result);
        }

        /// <summary>
        /// 移除工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        public async Task<JsonResult> Delete(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Remove(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 更新工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>

        [HttpPost("Update")]
        public async Task<JsonResult> Update(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Update(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 暂停工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("Pause")]
        public async Task<JsonResult> Pause(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Pause(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 开启工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("Start")]
        public async Task<JsonResult> Start(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Start(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 开启所有工作任务
        /// </summary>
        /// <returns></returns>
        [HttpPost("StartAll")]
        public async Task<JsonResult> StartAll()
        {
            return new JsonResult(await schedulerFactory.StartAll());
        }

        /// <summary>
        /// 重新加载配置启动后台任务
        /// </summary>
        /// <returns></returns>
        [HttpPost("Init")]
        public async Task<JsonResult> Init()
        {
            return new JsonResult(await schedulerFactory.Init());
        }

        /// <summary>
        /// 立即执行工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("Run")]
        public async Task<JsonResult> Run(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Run(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 停止工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("Stop")]
        public async Task<JsonResult> Stop(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.Stop(mySqlSugar, taskOptions));
        }

        /// <summary>
        /// 停止所有工作任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [HttpPost("StopAll")]
        public async Task<JsonResult> StopAll(QuzrtTaskOptions taskOptions)
        {
            return new JsonResult(await schedulerFactory.StopAll(mySqlSugar));
        }

        /// <summary>
        /// 导出数据信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet("ExportData")]
        public async Task<IActionResult> ExportData(QuzrtTaskOptions query)
        {
            return await Task.Factory.StartNew<IActionResult>(() =>
            {
                var data = schedulerFactory.GetJobs(mySqlSugar, query).GetAwaiter().GetResult();
                string excelName = string.Format("系统后台作业信息统计表");
                if (data.count > 0)
                {
                    var list = data.data as List<QuzrtTaskOptions>;
                    string fileName = webHost.WebRootPath + "\\template\\report\\quartz.xls";
                    string msg = string.Empty;
                    var ms = QuartzExport.ExportData(fileName, excelName, list, out msg);
                    if (string.IsNullOrEmpty(msg) && list.Count > 0 && ms != null)
                    {
                        return File(ms.ToArray(), "application/ms-excel", excelName + ".xls");
                    }
                    else
                    {
                        return File(new byte[] { }, "application/ms-excel", excelName + ".xls");
                    }
                    //else
                    //{
                    //    throw new Exception(msg);
                    //}
                }
                return File(new byte[] { }, "application/ms-excel", excelName + ".xls");
            });
        }
    }
}
